import { constantRoutes } from '@/router'
import Layout from '@/layout'
import sysMenuApi from '@/api/system/sys-menu'

/**
 * 当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归routers
 * 路由asyncRoutes过滤异步路由表
 */
export function filterAsyncRoutes(routes) {
  const res = []
  // 遍历菜单
  routes.forEach(route => {
    const tmp = { ...route }
    // 转换为对象
    if (tmp.component === 'Layout') {
      tmp.component = Layout
    } else {
      // 构造懒加载路由
      tmp.component = LoadView(tmp.component)
    }
    // 递归路由是否有子菜单 后端传递了个空集合需要加判断 tmp.children[0]
    if (tmp.children && tmp.children[0]) {
      tmp.children = filterAsyncRoutes(tmp.children)
    }
    res.push(tmp)
  })
  return res
}

/**
 * 构造懒加载路由
 * @param view 路由路径
 * @constructor 构造好的路径
 */
export const LoadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/**
 * 动态路由加载
 * @type {{generateRoutes({commit?: *}): Promise<unknown>}}
 */
const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      // 后端加载构造好的路由
      sysMenuApi.getRouters().then(res => {
        // 开始构造路由菜单
        const routerList = res.data
        const accessedRoutes = filterAsyncRoutes(routerList)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  hasPermission
}
